//
//  CashWithdrawalViewController.m
//  MagicZhao
//
//  Created by hy002 on 2017/12/11.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "CashWithdrawalViewController.h"
#import "BankModel.h"
#import "SYPasswordView.h"
#import "RetrievePasswordViewController.h"
#import "DrawSuccessViewController.h"
#import "AddCarViewController.h"

static NSString *cellPath = @"cashWithCell";
@interface CashWithdrawalViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,PayPassWordDelegate>
@property (nonatomic, strong)UITextField *moneyField;
@property (nonatomic, strong)UILabel *allMonerLab;
@property (nonatomic, strong)NSDictionary *bankDic;
@property (nonatomic, strong)UILabel *notCar;
@property (nonatomic, strong)UIImageView *carimgView;
@property (nonatomic, strong)UILabel *bankNameLab;
@property (nonatomic, strong)UILabel *carNumLab;
@property (nonatomic, strong)NSArray *carAry;
@property (nonatomic, assign)BOOL isHaveCar;
@property (nonatomic, strong)UIView *blackView;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)BankModel *bankModel;
@property (nonatomic, strong)UIView *payPassView;
@property (nonatomic, strong)SYPasswordView *pasView;

@end

@implementation CashWithdrawalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _bankDic = @{@"1002":@"gongsh",@"1005":@"nongh",@"1026":@"zhongguoy",@"1003":@"jianha",@"1001":@"zhaos",@"1066":@"youzheng",@"1020":@"jiaot",@"1004":@"puf",@"1006":@"mins",@"1009":@"xingy",@"1010":@"pinganyh",@"1021":@"zhongx",@"1025":@"huax",@"1027":@"guangf",@"1022":@"guangd",@"1032":@"beij",@"1056":@"ningb"};
    [self creatUI];
    [self requestBankCarList:nil];
}

- (void)creatUI
{
    self.view.backgroundColor = BacksColor;
    self.navigationItem.title = @"提现";
    self.navigationController.navigationBar.translucent = NO;
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 270*displaywidth)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    UIButton *drawalBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , 300*displaywidth, SCREEN_WIDTH-120*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(drawalBalanceAction) Title:@"提现" Font:15.0];
    [drawalBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    drawalBtn.backgroundColor = ThemeColor;
    [drawalBtn.layer setMasksToBounds:YES];
    [drawalBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:drawalBtn];
    
    UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 30*displaywidth, SCREEN_WIDTH-30*displaywidth, 30*displaywidth) Font:18.0 Text:@"提现金额" Color:RGB(77, 77, 77)];
    [whiteView addSubview:titLab];
    UILabel *imgLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 70*displaywidth, 30*displaywidth, 35*displaywidth) Font:25.0 Text:@"￥" Color:RGB(77, 77, 77)];
    [whiteView addSubview:imgLab];
    
    self.moneyField = [ZCControl createTextFieldWithFrame:CGRectMake(45*displaywidth, 70*displaywidth, SCREEN_WIDTH-145*displaywidth, 35*displaywidth) placeholder:@"" passWord:NO leftImageView:nil rightImageView:nil Font:25.0];
    [_moneyField setValue:RGB(179, 179, 179) forKeyPath:@"_placeholderLabel.textColor"];
    _moneyField.textColor = RGB(77, 77, 77);
    _moneyField.delegate = self;
    _moneyField.keyboardType = UIKeyboardTypeDecimalPad;
    [_moneyField becomeFirstResponder];
    [whiteView addSubview:_moneyField];
    UIButton *rightBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-100*displaywidth, 70*displaywidth, 100*displaywidth, 35*displaywidth) ImageName:nil Target:self Action:@selector(allMoneyAction) Title:@"全部提现" Font:18.0];
    rightBtn.backgroundColor = [UIColor clearColor];
    [rightBtn setTitleColor:RGB(238, 103, 94) forState:UIControlStateNormal];
    [whiteView addSubview:rightBtn];
    
    self.allMonerLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 125*displaywidth, SCREEN_WIDTH-30*displaywidth, 25*displaywidth) Font:15.0 Text:[NSString stringWithFormat:@"可提现金额￥%@",_myMoney] Color:RGB(153, 153, 153)];
    [whiteView addSubview:_allMonerLab];
    UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(0, 169*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
    lineAview.backgroundColor = LinesColor;
    [whiteView addSubview:lineAview];
    
    self.notCar = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 200*displaywidth, SCREEN_WIDTH-30*displaywidth, 40*displaywidth) Font:18.0 Text:@"请添加银行卡" Color:RGB(77, 77, 77)];
    _notCar.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:_notCar];
    
    self.carimgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 195*displaywidth, 50*displaywidth, 50*displaywidth) ImageName:@""];
    _carimgView.contentMode = UIViewContentModeScaleAspectFit;
    _carimgView.hidden = YES;
    [whiteView addSubview:_carimgView];
    
    self.bankNameLab = [ZCControl createLabelWithFrame:CGRectMake(85*displaywidth, 185*displaywidth*displaywidth, SCREEN_WIDTH-115*displaywidth, 35*displaywidth) Font:18.0 Text:@"" Color:RGB(77, 77, 77)];
    _bankNameLab.hidden = YES;
    [whiteView addSubview:_bankNameLab];
    
    self.carNumLab = [ZCControl createLabelWithFrame:CGRectMake(85*displaywidth, 220*displaywidth*displaywidth, SCREEN_WIDTH-115*displaywidth, 35*displaywidth) Font:18.0 Text:@"" Color:RGB(77, 77, 77)];
    _carNumLab.hidden = YES;
    [whiteView addSubview:_carNumLab];
    
    UIImageView *imageView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 205*displaywidth, 20*displaywidth, 30*displaywidth) ImageName:@"gs_icon05"];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [whiteView addSubview:imageView];
    UIButton *closeCarBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 170*displaywidth, SCREEN_WIDTH, 100*displaywidth) ImageName:nil Target:self Action:@selector(closeCarAction) Title:nil Font:12.0];
    closeCarBtn.backgroundColor = [UIColor clearColor];
    [whiteView addSubview:closeCarBtn];
    self.blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _blackView.backgroundColor = RGBA(0, 0, 0, 0.5);
    _blackView.hidden = YES;
    [sharedDelegate.window addSubview:_blackView];
    UITapGestureRecognizer *tap11 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ggViewPressed)];
    tap11.delegate = self;
    [_blackView addGestureRecognizer:tap11];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(50*displaywidth, SCREEN_HEIGHT/2-80*displaywidth, SCREEN_WIDTH-100*displaywidth, 100*displaywidth) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    //    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = [UIColor whiteColor];
    _tableview.layer.cornerRadius = 10;
    _tableview.layer.masksToBounds = YES;
    [_blackView addSubview:_tableview];
}

- (void)ggViewPressed
{
    _blackView.hidden = YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:_tableview]) {
        return NO;
    }
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _carAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_carAry.count > 0)
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        BankModel *model = _carAry[indexPath.row];
        NSString *backImg = @"zhongguoy";
        if ([_bankDic.allKeys containsObject:model.bankId])
        {
            backImg = _bankDic[model.bankId];
        }
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(20*displaywidth, 15*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:backImg];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        [cell.contentView addSubview:imgView];
        NSInteger lenth = model.cardNum.length;
        NSString *carNum = @"0000";
        if (lenth > 4)
        {
            carNum = [model.cardNum substringFromIndex:lenth-4];
        }
        UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(45*displaywidth, 10*displaywidth, SCREEN_WIDTH-180*displaywidth, 30*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"%@ %@ (%@)",model.bank,@"",carNum] Color:RGB(77, 77, 77)];
        [cell.contentView addSubview:namelab];
        
    }
    
    
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BankModel *model = _carAry[indexPath.row];
    if ([_bankDic.allKeys containsObject:model.bankId])
    {
        _carimgView.image = [UIImage imageNamed:_bankDic[model.bankId]];
    }
    _bankNameLab.text = model.bank;
    if (model.cardNum.length > 4)
    {
        NSString *carLastStr = [model.cardNum substringFromIndex:model.cardNum.length-4];
        _carNumLab.text = [NSString stringWithFormat:@"尾号%@储蓄卡",carLastStr];
    }
    _bankModel = model;
    _blackView.hidden = YES;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-100*displaywidth, 50*displaywidth)];
    myView.backgroundColor = [UIColor whiteColor];
    UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(10*displaywidth, 17.5*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"backimg" Target:self Action:@selector(backAction) Title:nil Font:12.0];
    backBtn.backgroundColor = [UIColor clearColor];
    [myView addSubview:backBtn];
    UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 10*displaywidth, SCREEN_WIDTH-170*displaywidth, 30*displaywidth) Font:15.0 Text:@"选择银行卡" Color:RGB(77, 77, 77)];
    titlab.textAlignment = NSTextAlignmentCenter;
    [myView addSubview:titlab];
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 49*displaywidth, SCREEN_WIDTH-100*displaywidth, 1*displayheight)];
    lineview.backgroundColor = LinesColor;
    [myView addSubview:lineview];
    return myView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*displaywidth;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50*displaywidth;
}

//选择银行卡
- (void)closeCarAction
{
    [self.view endEditing:YES];
    if (_isHaveCar)
    {
        if (_carAry.count > 0)
        {
            _blackView.hidden = NO;
            [_tableview reloadData];
        }
    }
    else
    {
        AddCarViewController *vc = [[AddCarViewController alloc] init];
        vc.isTixian = YES;
        WEAKSELF;
        vc.addBlock = ^(BankModel *model) {
            weakSelf.bankModel = model;
            [weakSelf requestBankCarList:model];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)backAction
{
    _blackView.hidden = YES;
}


//提现
- (void)drawalBalanceAction
{
    [self.view endEditing:YES];
    if ([_moneyField.text floatValue] == 0)
    {
        [LTools showMBProgressWithText:@"请输入提现金额" addToView:self.view];
        return;
    }
    if ([_moneyField.text floatValue] > [_myMoney floatValue])
    {
        [LTools showMBProgressWithText:@"不得超过可提现金额" addToView:self.view];
        return;
    }
    if ([_bankModel.ID integerValue] < 1)
    {
        [LTools showMBProgressWithText:@"请选择银行卡" addToView:self.view];
        return;
    }
    [self creatPayPassWordView];
    
}

- (void)creatPayPassWordView
{
    if (!self.payPassView)
    {
        self.payPassView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _payPassView.backgroundColor = RGBA(0, 0, 0, 0.5);
        [sharedDelegate.window addSubview:_payPassView];
        UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 230*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-230*displaywidth)];
        secondView.backgroundColor = RGB(242, 242, 242);
        [_payPassView addSubview:secondView];
        UILabel *titleLabel = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2-80*displaywidth, 0, 160*displaywidth, 44*displaywidth) Font:15.0 Text:@"请输入密码" Color:RGB(77, 77, 77)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [secondView addSubview:titleLabel];
        UIButton *contactBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-45*displaywidth, 12*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"chacha" Target:self Action:@selector(contactAction) Title:nil Font:13.0];
        contactBtn.backgroundColor = [UIColor clearColor];
        [secondView addSubview:contactBtn];
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 44*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineview.backgroundColor = RGB(210, 210, 210);
        [secondView addSubview:lineview];
        //        UILabel *moneyLabel = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 55*displaywidth, SCREEN_WIDTH-30*displaywidth, 25*displaywidth) Font:15.0 Text:@"充值金额 2000" Color:RGB(77, 77, 77)];
        //        moneyLabel.textAlignment = NSTextAlignmentCenter;
        //        [secondView addSubview:moneyLabel];
        self.pasView = [[SYPasswordView alloc] initWithFrame:CGRectMake(15*displaywidth, 90*displaywidth, SCREEN_WIDTH-30*displaywidth, 44*displaywidth)];
        _pasView.delegate = self;
        [secondView addSubview:_pasView];
        UIButton *forgotBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-115*displaywidth, 150*displaywidth, 100*displaywidth, 20*displaywidth) ImageName:nil Target:self Action:@selector(FindPassword) Title:@"忘记密码" Font:13.0];
        [forgotBtn setTitleColor:RGB(255, 111, 28) forState:UIControlStateNormal];
        [secondView addSubview:forgotBtn];
    }
    _payPassView.hidden = NO;
    [_pasView.textField becomeFirstResponder];
}
- (void)shuruSuccessValue:(NSString *)value
{
    [self requestPublicKey:value];
    NSLog(@"密码-----%@",value);
}

- (void)requestPublicKey:(NSString *)passWorld
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];
    [HYBaseHandler requestPublicKeyParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             NSString *publicKey = obj[@"data"];
             //测试要加密的数据
             NSString *sourceStr = passWorld;
             //公钥加密
             NSString *encryptStr = [RSA encryptString:sourceStr publicKey:publicKey];
             NSDictionary *dic = @{@"bankCardId":weakSelf.bankModel.ID,
                                   @"money":weakSelf.moneyField.text,
                                   @"password":encryptStr
                                   };
             [weakSelf requestWalletPay:dic];
             
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
             [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
     }];
}
//找回密码
- (void)FindPassword
{
    _payPassView.hidden = YES;
    [self.pasView endEditing:YES];
    [self.pasView clearUpPassword];
    RetrievePasswordViewController *Vc = [[RetrievePasswordViewController alloc] init];
    Vc.titleString = @"忘记密码";
    [self.navigationController pushViewController:Vc animated:YES];
}

- (void)contactAction
{
    _payPassView.hidden = YES;
    [self.pasView endEditing:YES];
    [self.pasView clearUpPassword];
}

- (void)requestWalletPay:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestWithdrawAddParmers:dic Success:^(id obj)
    {
        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
        if ([obj server_Getcodecheck])
        {
            weakSelf.payPassView.hidden = YES;
            weakSelf.payPassView = nil;
            [weakSelf.pasView endEditing:YES];
            [weakSelf.pasView clearUpPassword];
            [weakSelf.payPassView removeFromSuperview];
            DrawSuccessViewController *vc = [[DrawSuccessViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

    }];
}

//全部提现
- (void)allMoneyAction
{
    [self.view endEditing:YES];
    _moneyField.text = [NSString stringWithFormat:@"%@",_myMoney];
}

- (void)requestBankCarList:(BankModel *)closeModel
{
    WEAKSELF;
    [HYBaseHandler requestBankCarListParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.carAry = [BankModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
             if (weakSelf.carAry.count > 0)
             {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     weakSelf.notCar.hidden = YES;
                     weakSelf.carimgView.hidden = NO;
                     weakSelf.bankNameLab.hidden = NO;
                     weakSelf.carNumLab.hidden = NO;
                     weakSelf.isHaveCar = YES;
                     BankModel *model = weakSelf.carAry[0];
                     if (closeModel != nil)
                     {
                         model = closeModel;
                         
                     }
                     weakSelf.bankModel = model;
                     if ([_bankDic.allKeys containsObject:model.bankId])
                     {
                         weakSelf.carimgView.image = [UIImage imageNamed:_bankDic[model.bankId]];
                     }
                     weakSelf.bankNameLab.text = model.bank;
                     if (model.cardNum.length > 4)
                     {
                         NSString *carLastStr = [model.cardNum substringFromIndex:model.cardNum.length-4];
                         weakSelf.carNumLab.text = [NSString stringWithFormat:@"尾号%@储蓄卡",carLastStr];
                     }
                     CGFloat h = (weakSelf.carAry.count+1)*50*displaywidth;
                     if (h > 250*displaywidth)
                     {
                         h = 250*displaywidth;
                     }
                     weakSelf.tableview.frame = CGRectMake(50*displaywidth, SCREEN_HEIGHT/2-h/2-30*displaywidth, SCREEN_WIDTH-100*displaywidth, h);
                     [weakSelf.tableview reloadData];
                 });
             }
             else
             {
                 weakSelf.notCar.hidden = NO;
                 weakSelf.carimgView.hidden = YES;
                 weakSelf.bankNameLab.hidden = YES;
                 weakSelf.carNumLab.hidden = YES;
                 weakSelf.isHaveCar = NO;

             }
             
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
         
     } failed:^(NSError *error) {
         
     }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
